package com.xiaoxu.springboot.filter;

import com.xiaoxu.springboot.listener.LoginListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;

@WebFilter
public class ParamFilter implements Filter {
    private final static Logger LOGGER = LoggerFactory.getLogger(ParamFilter.class);
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        LOGGER.debug("====init filter===");
        Filter.super.init(filterConfig);

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        LOGGER.debug("===do filter===");
        //将ServletRequest等转化为httpServletRequest等
        HttpServletRequest req=(HttpServletRequest) servletRequest;
        HttpServletResponse resq=(HttpServletResponse) servletResponse;
        //因为httpServletRequest不能直接操作ParameterMap，所以构建wrapper对象来构建
        HttpServletRequestWrapper wrapper=new HttpServletRequestWrapper(req){
            //重写wrapper对象的getParameter方法，替换脏字符串
            @Override
            public String getParameter(String name) {
                String value=super.getParameter(name);
                return value.replace("fuck","***");
            }

            @Override
            public String[] getParameterValues(String name) {
                String[] values=super.getParameterValues(name);
                return Arrays.asList(values)
                        .stream()
                        .map(item-> item.replaceAll("fuck","****"))
                        .toArray(String[] :: new);
            }
        };
        //将wrapper和response交出去
        filterChain.doFilter(wrapper,resq);

    }

    @Override
    public void destroy() {
        LOGGER.debug("===Destory filter===");
        Filter.super.destroy();
    }
}
